<?php
/*
 * 数据库
 */
class MySqlDb{
	//连接数据库资源
	private $mysqli;
	//单例对象引用
	private static $mySqlDb;
	//数据库连接信息
	private $dbConfig = array(
			'host' => 'localhost',				//主机
			'port' => '3306',					//端口
			'user' => 'root',					//用户
			'password' => 'lanxuewei0227',		//密码
			'charset' => 'utf8',				//字符集
			'dbname' => 'select_course_system' 	//默认数据库
	);
	
	/* 	//初始化属性，数据库连接信息
	 private function initDbConfig($params){
	 //初始化属性,使用array_marge()函数合并两个数组
	 $this->dbConfig = arrary_marge($this->dbConfig, $params);
	 } */
	
	//构造方法(私有化，单例模式)
	private function __construct(){
		//初始化属性
		//$this->initDbConfig();
		//连接数据库
		$this->connectServer();
		//设定字符集
		$this->setCharSet();
		//选择默认数据库
		$this->selectDefaultDb();
	}
	
	//连接目标服务器
	private function connectServer(){
		
		$host = $this->dbConfig['host'];
		$port = $this->dbConfig['port'];
		$user = $this->dbConfig['user'];
		$password = $this->dbConfig['password'];
		
		$this->mysqli = new mysqli("$host:$port", $user, $password);
		//连接数据库
		if(mysqli_connect_errno()){
			die('数据库服务器连接失败,请确认连接失败信息！'.mysqli_connect_errno());
		}
	}
	
	//选择字符集
	private function setCharSet(){
		$sql = "set names {$this->dbConfig['charset']}";
		$this->query($sql);
	}
	
	//选择默认数据库
	private function selectDefaultDb(){
		//判断$this->dbConfig['dbname']是否为空,为空,表示不需要选择数据库
		if($this->dbConfig['dbname'] == ''){
			return;
		} else {
			$sql = "use `{$this->dbConfig['dbname']}`";
			$this->query($sql);
		}
	}
	
	
	//获得单例对象的公共接口
	public static function getMySqlDb(){
		//判断是否没有被实例化过
		if(!self::$mySqlDb instanceof self){
			//实例化并保存
			self::$mySqlDb = new self();
		}
		//返回对象
		return self::$mySqlDb;
	}
	
	//私有克隆
	private function __clone(){
		
	}
	
	//执行sql
	public function query($sql){
		if($result = mysqli_query($this->mysqli, $sql)){
			//执行成功
			return $result;
		} else {
			//设定失败
			echo 'SQL执行失败：</br>';
			echo '错误的SQL为：', $sql, '</br>';
			echo '错误的代码为：', mysqli_errno($this->mysqli), '</br>';
			echo '错误的信息为：', var_dump(mysqli_error_list($this->mysqli)),'</br>';
			die;
		}
	}
	
	//查询单条记录
	public function fetchRow($sql){
		//执行sql
		if($result = $this->query($sql)){
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			//释放结果集
			mysqli_free_result($result);
			return $row;
		} else {
			//执行失败
			return false;
		}
	}
	
	//处理多条数据
	public function fetchAll($sql){
		if($result = $this->query($sql)){
			$rows = array();
			while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
				$rows[] = $row;
			}
			//释放结果集
			mysqli_free_result($result);
			return $rows;
		} else {
			//执行失败
			return false;
		}
	}
	
	//转义
	public function escapeString($data){
		return mysqli_real_escape_string($this->mysqli, $data);
	}
}

/* class test{
 public function show(){
 echo "I am test!";
 }
 } */
?>
